package de.jmda.core.mproc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;

import de.jmda.core.util.JavaCompilerUtil;

/**
 * Utility class to launch jMDA style annotation processing.
 */
public abstract class Launcher
{
	/**
	 * Launches annotation processors for Java source files (both stored in <code>
	 * launchConfiguration</code>) via <code>JavaCompiler</code> with <code>
	 * -proc:only</code> option. Each annotation processor specified in {@link
	 * LaunchConfiguration#processors} will be invoked during the compilation.
	 *
	 * @param launchConfiguration storage of processors and files
	 * @return value of {@link CompilationTask#call()}
	 * @throws IOException
	 */
	public static boolean launch(LaunchConfiguration launchConfiguration)
			throws IOException
	{
		JavaCompiler javaCompiler = JavaCompilerUtil.createJavaCompiler();

		StandardJavaFileManager standardJavaFileManager =
				javaCompiler.getStandardFileManager(null, null, null);

		// create a diagnostic controller, which holds the compilation problems
		//		DiagnosticCollector<JavaFileObject> diagnostics =
		//				new DiagnosticCollector<JavaFileObject>();
		DiagnosticCollector<JavaFileObject> diagnostics = null;

		List<String> options = new ArrayList<String>();

		options.add("-proc:only");

		try
		{
			Iterable<? extends JavaFileObject> fileObjects =
					standardJavaFileManager.getJavaFileObjectsFromFiles(
							launchConfiguration.files);

			CompilationTask compilationTask =
					javaCompiler.getTask(
							null,
							standardJavaFileManager,
							diagnostics,
							options,
							null,
							fileObjects);

			compilationTask.setProcessors(launchConfiguration.processors);

			Processor.FILES_TO_PROCESS.clear();
			Processor.FILES_TO_PROCESS.addAll(launchConfiguration.files);

			return compilationTask.call();
		}
		finally
		{
			standardJavaFileManager.close();
		}
	}
}